const User = require('../model/mongo/user.model');
const { generateToken } = require('../utils/jwt');

// 用户登录
const login = async (ctx) => {
  try {
    const { username, password } = ctx.request.body;

    // 查找用户
    const user = await User.findOne({ username }).populate('role');
    if (!user) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '用户名或密码错误'
      };
      return;
    }

    // 验证密码
    const isMatch = await user.matchPassword(password);
    if (!isMatch) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        message: '用户名或密码错误'
      };
      return;
    }

    // 检查用户状态
    if (user.status !== 1) {
      ctx.status = 403;
      ctx.body = {
        code: 403,
        message: '账号已被禁用'
      };
      return;
    }

    // 更新登录信息
    user.lastLoginTime = new Date();
    user.lastLoginIp = ctx.ip;
    await user.save();

    // 生成 token
    const token = generateToken({
      id: user._id,
      username: user.username,
      role: user.role
    });

    ctx.body = {
      code: 200,
      data: {
        token,
        userInfo: {
          id: user._id,
          username: user.username,
          nickname: user.nickname,
          avatar: user.avatar,
          role: user.role
        }
      },
      message: '登录成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

// 获取当前用户信息
const getCurrentUser = async (ctx) => {
  try {
    const user = await User.findById(ctx.state.user.id)
      .select('-password')
      .populate('role');

    if (!user) {
      ctx.status = 404;
      ctx.body = {
        code: 404,
        message: '用户不存在'
      };
      return;
    }

    ctx.body = {
      code: 200,
      data: user,
      message: '获取成功'
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: '服务器错误'
    };
  }
};

// 退出登录
const logout = async (ctx) => {
  ctx.body = {
    code: 200,
    message: '退出成功'
  };
};

module.exports = {
  login,
  getCurrentUser,
  logout
}; 